package com.scau.database.finalexam.controllers;


import com.scau.database.finalexam.DAO.DepartmentDao;
import com.scau.database.finalexam.DAO.EmployeeDao;
import com.scau.database.finalexam.beans.Department;
import com.scau.database.finalexam.beans.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeDao employeeDao;
    @Autowired
    DepartmentDao departmentDao;

    //查询所有员工
    @RequestMapping("/emps")
    public String list(Model model){

        Collection<Employee> employees = employeeDao.getAll();
        model.addAttribute("emps",employees);
        return "emp/list";
    }

    //添加页面
    @GetMapping("/emp")
    public String toAddPage(Model model){

        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts",departments);
        return  "emp/add";
    }


    //SpringMVC 自动封装 请求参数和入参的对象属性名是一样的
    @PostMapping("/emp")
    public String addEmp(Employee employee){

//        System.out.println("员工信息" + employee);
//        employeeDao.save(employee);
        System.out.println("修改");
        //redirect   "/"表示当前项目
        //forword
        return "redirect:/emps";
    }

    @GetMapping("/emp/{id}")
    public String toEditPage(@PathVariable("id") Integer id,Model model){
        Employee employee = employeeDao.get(id);
        model.addAttribute("emp",employee);

        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts",departments);
        //回到修改页面
        //2合1
        return "emp/add";
    }

    //修改
    @PutMapping("/emp")
    public  String updateEmployee(Employee employee){

        System.out.println(employee);
        employeeDao.save(employee);
        return "redirect:/emps";

    }

    //员工删除
//    @DeleteMapping("/emp/{id}")
//    public String deleteEmployee(@PathVariable("id") Integer id){
//        System.out.println("id "+id);
//        //employeeDao.delete(id);
//        return "emps";
//
//    }

//    @DeleteMapping("/emp/{id}")
//    public String addE(Employee employee){
//
//        System.out.println("删除");
//
//        return "redirect:/emps";
//    }

    @DeleteMapping("/emp/{id}")
    public String addEmployee(@PathVariable("id") Integer id){

        employeeDao.delete(id);
        System.out.println("删除");

        return "redirect:/emps";
    }
    @PostMapping("/emp/{id}")
    public String addEmploy(@PathVariable("id") Integer id){
        employeeDao.delete(id);
        System.out.println("删除");
        return "redirect:/emps";
    }

}
